package Controllers;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;

import Bean.BeanUser;
import Impl.UserServiceImpl;
import exception.BooksNotFoundException;

@Controller
public class ShowUserByKeywordController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    UserServiceImpl userService;
	 @RequestMapping("/ShowUserbyKeyword")
		protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
			// TODO Auto-generated method stub
	    	response.setContentType("text/html;charset=UTF-8");  
	    	JSONArray arr = new JSONArray();
	    	ApplicationContext applicationContext=(ApplicationContext)request.getSession().getServletContext().getAttribute("ctx");
	        userService=(UserServiceImpl)applicationContext.getBean("UserServiceImpl");
			ArrayList<BeanUser> users;
			String keyword=request.getParameter("keyword");
			keyword=keyword.replaceAll("'", "");
			try {
				users = userService.getUsersByKeyword(keyword);
				for(BeanUser user:users) {
					arr.add(user.toJson());
				}
			} catch (BooksNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.getWriter().append(arr.toJSONString());
		}
}
